/**
 * Copyright ©2012-2018 HopeHaiyang Corporation, All Rights Reserved
 * http://www.wuhanhope.com
 */
package hujia.profile.server.img;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * class info
 *
 * @author hujia
 *         Create at 2018/7/31 9:24
 */
@Service
public class AuthenticationProviderImg implements AuthenticationProvider {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String username = token.getName();
        UserDetails userDetails = null;
        if (username != null) {
            userDetails = this.userDetailsService.loadUserByUsername(username);
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException("not found user!");
        } else if (!userDetails.isEnabled()) {
            throw new DisabledException("user disable");
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("user expire");
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException("user locked");
        } else if (!userDetails.isCredentialsNonExpired()) {
            throw new LockedException("credential expire");
        }
        // BCryptPasswordEncoder bCryptPasswordEncoder = new
        // BCryptPasswordEncoder(16);
        if (!userDetails.getPassword().equals(token.getCredentials())) {
            throw new BadCredentialsException("Invalid username/password");
        }

        return new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(),
                userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }
}
